package com.mediacloud.app.newsmodule.fragment.video.x

import android.animation.Animator
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Rect
import android.net.ConnectivityManager
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eventTrack.TXReportManager
import com.mediacloud.app.assembly.util.buildUrl
import com.mediacloud.app.model.OnVideoPause
import com.mediacloud.app.model.OnVideoPlayerPause
import com.mediacloud.app.model.OnVideoPlayerPause2
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.BigVideoViewHolder
import com.mediacloud.app.newsmodule.fragment.video.vod.XListPlayer
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.XKey
import com.tencent.mmkv.MMKV
import com.utils.SystemServiceManager
import com.yoake.media.player.XPlayer
import com.yoake.media.player.controller.component.PrepareView
import com.yoake.media.player.utils.OnPlayerActionListener
import com.yoake.media.player.utils.XVideoBitRate
import com.yoake.media.player.utils.XVideoItem
import com.yoake.media.player.utils.XVideoSpeed
import com.yoake.media.player.utils.interfaces.PendingPlayerChangeListener
import com.zimeiti.details.MediaAuthorDetailActivity
import kotlinx.android.synthetic.main.activity_video_prew.durationTv
import kotlinx.android.synthetic.main.activity_video_prew.logoLayout
import kotlinx.android.synthetic.main.activity_video_prew.player
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import xyz.doikki.videoplayer.player.BaseVideoView
import xyz.doikki.videoplayer.player.BaseVideoView.OnStateChangeListener
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.util.PlayerUtils
import java.util.concurrent.atomic.AtomicBoolean

class RVListVideoKit(val context: Context, var recyclerView: RecyclerView,val owner: LifecycleOwner) : BaseVideoView.OnStateChangeListener, LifecycleEventObserver {

    val playerView: XListPlayer = XListPlayer(context,owner)
    var player: XPlayer = playerView.p
    private var container: FrameLayout? = null
    private var logoView: View? = null
    private var logoAminListener = LogoViewAnimListener()
    private var playerAminListener = PlayerAnimListener()
    private var logoAnim: Animator? = null
    private var playAnim: Animator? = null
    private var pendingExecuteRenderAnimator = AtomicBoolean(false)
    var firstVisibleItem = 0
    var lastVisibleItem: Int = 0
    var mDy = 0
    val rect = Rect()
    var autoPlay = true
    //用于横竖屏切换造成RecyclerView高度改变，会回调onScrolled()
    var pendingPlayerChange = false
    var pendingStopPlay = false
    var pendingStopTimeStamp = 0L
    var item: ArticleItem? = null
    var shareWrap: ShareWrap? = null

    init {
        if (context is LifecycleOwner) {
            context.lifecycle.addObserver(this)
        }
        shareWrap = ShareWrap(context, false)
        shareWrap?.setShowFunction(true)
        player.hidePreparingLoadingView = true
        player.prepareView.fadeOutAnimMoment =PrepareView.FADE_OUT_ANIM_OFF
        EventBus.getDefault().register(this)
        player.addOnStateChangeListener(this)
        player.bottomControl.setPendingPlayerChangeListener(object : PendingPlayerChangeListener {
            override fun onPendingPlayerStateChange() {
                pendingPlayerChange = true
            }
        })
        playerView.p.setOnTitleMoreClickListener {
            shareWrap?.init(item, CatalogItem())
            if (player.isFullScreen) {
                player.controller.getControllerInstance()?.hide()
            }
            shareWrap?.show(player)
        }
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        if(pendingStopPlay)return
                        initPendingPlay()

                    }
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        pendingStopPlay = false
                    }
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (player.isFullScreen) return
                if (pendingPlayerChange) {
                    pendingPlayerChange = false
                    return
                }
                mDy = dy
                if (container != null) {
                    container!!.getLocalVisibleRect(rect)
                    if (rect.top != 0 || rect.bottom - rect.top < container!!.measuredHeight) {
                        Log.w("RVLIST", "移除容器 ${container.hashCode()}")
                        reset()
                    }
                }
            }
        })
        player.onPlayerActionListener = object :OnPlayerActionListener{
            override fun onBitRateChange(before: XVideoBitRate?, after: XVideoBitRate) {

            }

            override fun onDamuSwitch(isOpen: Boolean) {
                item?.let{
                    if (isOpen){

                    }else{

                    }
                }

            }

            override fun onPlayerStateChanged(playerState: Int) {
                val isFullScreen = playerState == VideoView.PLAYER_FULL_SCREEN
            }

            override fun onProjectionScreen() {
                //投屏回调
            }

            override fun onSeekTo(isForward: Boolean) {
                item?.let{
                    if (isForward){


                    }else{

                    }
                }


            }

            override fun onSpeedChange(before: XVideoSpeed?, after: XVideoSpeed) {

            }


        }
    }

     fun setOnclick() {
        recyclerView.adapter?.let {
            for (i in 0..it.itemCount - 1) {
                val holder = recyclerView.findViewHolderForAdapterPosition(i)
                if (holder is IVideoHolder) {
                    holder.getPlayActionView()?.setOnClickListener {
                        if (container == holder.getContainer()) return@setOnClickListener
                        if (context is MediaAuthorDetailActivity) {
                            TXReportManager.getInstance().app_jhapp_media_interact(
                                MediaAuthorDetailActivity.intentId,
                                MediaAuthorDetailActivity.intentName,
                                MediaAuthorDetailActivity.intentFansNumb,
                                MediaAuthorDetailActivity.intentLikeNum,
                                MediaAuthorDetailActivity.intentPublishNumb,
                                MediaAuthorDetailActivity.intentFollowStatus,
                                MediaAuthorDetailActivity.intentCurrentTab,
                                "点击播放"
                            )
                        }
                        //大图样式的视频holder
                        if (holder is BigVideoViewHolder) {
                            TXReportManager.getInstance().app_jhapp_video_interact(
                                "点击播放",
                                holder.getArticle()?.getCatalogName(),
                                holder.getArticle(),
                                i
                            )
                        }

                        container = holder.getContainer()
                        logoView = holder.getLogLayout()
                        holder.getArticle()?.let {
                            if (System.currentTimeMillis() - pendingStopTimeStamp > 300) {
                                logoAnim?.cancel()
                                logoView?.alpha = 1f
                                pendingStopPlay = false
                                intentPlay(it)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun checkNetType(): Boolean {
        val cm = SystemServiceManager.getConnectivityManager(context)
        val networkInfo = cm.activeNetworkInfo
        if (networkInfo != null && networkInfo.isAvailable) {
            mNetType = networkInfo.type
            return true
        }
        return false
    }

    var mNetType = 0

    fun initPendingPlay() {
        //无网络情况下不去播放了
        if (!checkNetType()){
            return
        }
        setOnclick()
        val isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false)
        if (!isAutoPlay && mNetType != ConnectivityManager.TYPE_WIFI) {
            return
        }
        val layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager) {
            firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
            lastVisibleItem = layoutManager.findLastVisibleItemPosition()
        } else if (layoutManager is LinearLayoutManager) {
            firstVisibleItem = layoutManager.findFirstVisibleItemPosition()
            lastVisibleItem = layoutManager.findLastVisibleItemPosition()
        }
        container?.let {
            //判断一下当前播放的item是否还处于完全可见状态
            it.getLocalVisibleRect(rect)
            if (rect.top == 0 && rect.bottom - rect.top >= it.measuredHeight) {
                return
            }
        }
        if (mDy > 0) {//列表页往下滚动
            for (i in firstVisibleItem..lastVisibleItem) {
                if (findPlayingViewHolder(i)) break
            }
        } else {//列表页往上滚动
            for (i in lastVisibleItem downTo firstVisibleItem) {
                if (findPlayingViewHolder(i)) break
            }
        }
    }

    private fun findPlayingViewHolder(position: Int): Boolean {
        val holder = recyclerView.findViewHolderForAdapterPosition(position)
        if (holder is IVideoHolder) {
//            holder.getPlayActionView()?.setOnClickListener {
//                if (container == holder.getContainer()) return@setOnClickListener
//                if (context is MediaAuthorDetailActivity){
//                    TXReportManager.getInstance().app_jhapp_media_interact(
//                        MediaAuthorDetailActivity.intentId,
//                        MediaAuthorDetailActivity.intentName,
//                        MediaAuthorDetailActivity.intentFansNumb,
//                        MediaAuthorDetailActivity.intentLikeNum,
//                        MediaAuthorDetailActivity.intentPublishNumb,
//                        MediaAuthorDetailActivity.intentFollowStatus,
//                        MediaAuthorDetailActivity.intentCurrentTab,
//                        "点击播放")
//                }
//                //大图样式的视频holder
//                if (holder is BigVideoViewHolder){
//                    TXReportManager.getInstance().app_jhapp_video_interact("点击播放", holder.getArticle()?.getCatalogName(), holder.getArticle(),position)
//                }
//
//                container = holder.getContainer()
//                logoView = holder.getLogLayout()
//                holder.getArticle()?.let {
//                    if (System.currentTimeMillis() - pendingStopTimeStamp > 300) {
//                        logoAnim?.cancel()
//                        logoView?.alpha = 1f
//                        pendingStopPlay = false
//                        intentPlay(it)
//                    }
//                }
//            }
            var settingAutoPlay = MMKV.defaultMMKV().getBoolean(XKey.AUTO_PLAY,false)
            if (autoPlay && settingAutoPlay) {
                holder.getContainer().getLocalVisibleRect(rect)
                if (rect.top == 0 && rect.bottom - rect.top >= holder.getContainer().measuredHeight) {
                    container = holder.getContainer()
                    logoView = holder.getLogLayout()
                    holder.getArticle()?.let {
                        if (System.currentTimeMillis() - pendingStopTimeStamp > 300) {
                            intentPlay(it)
                        }
                    }
                    return true
                }
            }
        }
        return false
    }

    fun intentPlay(item: ArticleItem) {
        this.item = item
        playerView.parent?.let {
            (it as ViewGroup).removeView(playerView)
        }
        player.alpha = 0.0f
        player.prepareView.mThumb.visibility = View.GONE
        player.prepareView.playBtn.visibility = View.GONE
        val params = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
        container?.addView(playerView, 0, params)

        player.setPoster(buildUrl(3, item.logo), ContextCompat.getDrawable(context, R.drawable.cctv7_loading_img))
        when (item.type) {
            TypeX.NEWS.LIVE_VIDEO -> player.setPlayerType(XPlayer.VIDEO_LIVE)
            else -> player.setPlayerType(XPlayer.VIDEO_VOD)
        }
        logoAnim = ObjectAnimator.ofFloat(logoView!!, "alpha", 0f)
        logoAnim?.duration = 500
        logoAnim?.interpolator = null
        logoAnim?.addListener(logoAminListener)
        logoAnim?.start()
        if (item.xVideoItem != null) {
            EventBus.getDefault().post(OnVideoPause())
            player.addVideoItem(item.xVideoItem, true)
        } else {
            try {
                val video = JSONObject(item.video)
                val tsAddress = VideoAddressGet.getAddress(video)
                if (tsAddress != null) {
                    val length = tsAddress.length()
                    val videoPlayObj = XVideoItem(item.getTitle())
                    videoPlayObj.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                    videoPlayObj.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                    val cdnEncypt = video.optString("cdnConfigEncrypt")
                    for (i in 0 until length) {
                        val line = tsAddress.optJSONObject(i)
                        val lineItem = XVideoBitRate()
                        lineItem.path = line.optString("url")
                        lineItem.title = line.optString("title")
                        lineItem.cdnEncypt = cdnEncypt
                        videoPlayObj.bitRates.add(lineItem)
                    }
                    val iterator = videoPlayObj.bitRates.iterator()
                    while (iterator.hasNext()) {
                        val v = iterator.next()
                        if (v.title?.contains("源码") == true) {
                            iterator.remove()
                        }
                    }
                    videoPlayObj.bitRates.reverse()
                    item.xVideoItem = videoPlayObj
                    EventBus.getDefault().post(OnVideoPause())
                    player.addVideoItem(item.xVideoItem, true)
                    player.addOnStateChangeListener(object:OnStateChangeListener{
                        override fun onPlayerStateChanged(p0: Int) {

                        }

                        override fun onPlayStateChanged(playState: Int) {
                            when (playState) {
                                VideoView.STATE_PAUSED-> {

                                }
                                VideoView.STATE_PREPARING->{

                                }
                                VideoView.STATE_PREPARED -> {

                                }
                            }
                        }

                    })
                }else{
                    reset()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }

    private fun executeRenderAnimator() {
        pendingExecuteRenderAnimator.set(false)
        playAnim = ObjectAnimator.ofFloat(player, "alpha", 1f)
        playAnim?.duration = 500
        playAnim?.interpolator = null
        playAnim?.addListener(playerAminListener)
        playAnim?.start()
    }

    /**
     * fragment 切走掉切走掉!!!其他地方不要掉
     */
    fun stopPlay() {
        pendingStopPlay = true
        pendingStopTimeStamp = System.currentTimeMillis();
        reset()
    }

    fun onDestroy() {
        if (context is LifecycleOwner) {
            context.lifecycle.removeObserver(this)
            if (player != null) {
                context.lifecycle.removeObserver(player)
            }
        }
        EventBus.getDefault().unregister(this)
        player.connectivityEngine.unregisterNetworkChangeListener()
        player.adImageView?.cancelCountDown()
        if (player.cdnUrl != null) {
            player.preloadManager.removePreloadTask(player.cdnUrl)
        }
        player.vRLibrary?.onDestroy()
    }

    fun reset() {

        playerView.parent?.let {
            val rl = it as ViewGroup
            rl.removeView(playerView)
        }
        player.release()
        container = null
        logoAnim?.cancel()
        playAnim?.cancel()
        logoView?.alpha = 1f
    }

    override fun onPlayerStateChanged(playerState: Int) {

    }


    override fun onPlayStateChanged(playState: Int) {
        Log.e("DDDFFF", "onPlayStateChanged $playState")
        when (playState) {
            VideoView.STATE_BUFFERED -> {
                if (pendingExecuteRenderAnimator.get()) {
                    executeRenderAnimator()
                }
            }
            VideoView.STATE_PREPARED -> {
                if (pendingStopPlay) {
                    reset()
                }
                if (System.currentTimeMillis() - pendingStopTimeStamp < 300) {
                    reset()
                }
            }
            VideoView.STATE_PLAYING -> {

                if (pendingExecuteRenderAnimator.get()) {
                    executeRenderAnimator()
                }
            }
            VideoView.STATE_PLAYBACK_COMPLETED -> {
                if (!player.isFullScreen) {
                    reset()
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onVideoPause(pause: OnVideoPlayerPause) {
        reset()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onVideoPause2(pause: OnVideoPlayerPause2) {
        reset()
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_PAUSE -> if (!player.isFullScreen) {
                reset()
            }
            Lifecycle.Event.ON_DESTROY -> player.release()
        }
    }

    inner class LogoViewAnimListener : Animator.AnimatorListener {
        override fun onAnimationStart(animation: Animator?) {

        }

        override fun onAnimationEnd(animation: Animator?) {
            if (player.currentPlayState == VideoView.STATE_PLAYING || player.currentPlayState == VideoView.STATE_BUFFERED) {
                executeRenderAnimator()
            } else {
                pendingExecuteRenderAnimator.set(true)
            }
        }

        override fun onAnimationCancel(animation: Animator?) {

        }

        override fun onAnimationRepeat(animation: Animator?) {

        }
    }


    inner class PlayerAnimListener : Animator.AnimatorListener {
        override fun onAnimationStart(animation: Animator?) {

        }

        override fun onAnimationEnd(animation: Animator?) {
            playerView.bringToFront()
            logoView!!.alpha = 1f
        }

        override fun onAnimationCancel(animation: Animator?) {

        }

        override fun onAnimationRepeat(animation: Animator?) {

        }
    }
}
